import * as WebSocket from "ws"
import { WebSocketRpcBridgeHost, IRpcSocketServer, RpcBridgeHost } from "rpc_dream";

export class RpcWebSocketServer implements IRpcSocketServer<WebSocket.Server> {
    onLaunch: () => void = null!
    onShutDown: () => void = () => {}
    public onClientConnected: (client: RpcBridgeHost<any>) => void = null!
    public onError: (error: Error) => void = error => {console.error(error)}
    public server: WebSocket.Server = null!
    public constructor (private serverCreator: () => Promise<WebSocket.Server>){

    }
    public async prepareForLaunch(): Promise<void> {
        const server = await this.serverCreator()
        server.on("error", error => {
            this.onError(error)
        })
        server.on("connection", clientSocket => {
            const host = new WebSocketRpcBridgeHost(async () => clientSocket as any)
            this.onClientConnected(host)
        })
        server.on("listening", () => {
            this.onLaunch()
        })
        server.on("close", () => {
            this.onShutDown()
        })
    }
    shutdown(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this.server.close(error => {
                if (error != null) reject(error)
                else resolve()
            })
        })
    }
}
